package com.cfl.springboot.service.impl;

import java.util.Random;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cfl.springboot.dao.UserMapper;
import com.cfl.springboot.model.User;
import com.cfl.springboot.service.UserService;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;
	
	public int login(String name, String password) throws Exception {
		try {
			User user = userMapper.selectByNameAndPassword(name	, password);
			if(user == null)
			{
				return -1;
			}
			return 0;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public void saveRegister(String name, String password) throws Exception {
		try {
			if(StringUtils.isBlank(name) || StringUtils.isBlank(password))
			{
				return;
			}
			User user = new User();
			user.setUid(UUID.randomUUID().toString());
			user.setName(name);
			user.setNickName(getRandomString(8));
			user.setPassword(password);
			user.setToken(UUID.randomUUID().toString());
			userMapper.insert(user);
		} catch (Exception e) {
			throw e;
		}
	}
	
	public User findByName(String name) throws Exception {
		try {
			return userMapper.selectByName(name);
		} catch (Exception e) {
			throw e;
		}
	}
	
	public static String getRandomString(int length) { //length表示生成字符串的长度
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }  
}
